package com.css.zfzx.sjcj.modules.app.controller;

import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.base.response.RestResponse;
import com.css.bpm.platform.org.division.repository.entity.DivisionEntity;
import com.css.bpm.platform.org.user.repository.entity.CertificationEntity;
import com.css.bpm.platform.org.user.repository.entity.UserEntity;
import com.css.bpm.platform.page.login.viewobjects.PwdCheck;
import com.css.bpm.platform.sys.syssubapp.repository.entity.SysSubappEntity;
import com.css.bpm.platform.sys.syssubapp.service.SysSubappService;
import com.css.bpm.platform.utils.PlatformRSAUtils;
import com.css.zfzx.sjcj.modules.app.service.AppLoginService;
import com.css.zfzx.sjcj.modules.app.vo.LoginParamVO;
import com.css.zfzx.sjcj.modules.app.vo.RegistUserVo;
import com.css.zfzx.sjcj.modules.app.vo.UpdatePwdVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/app")
public class AppController {
    @Autowired
    SysSubappService sysSubappService;
    @Autowired
    AppLoginService appLoginService;
    /***
     * App端登录
     * @param loginParamVO
     * @return
     */
    @PostMapping("/doLogin")
    public RestResponse doLogin(HttpServletRequest request, @RequestBody LoginParamVO loginParamVO) {
        String userName = loginParamVO.getUserName();
        String password = loginParamVO.getPassword();
        String appCode = loginParamVO.getAppCode();

        if (StringUtils.isEmpty(userName)) {
            return RestResponse.fail("用户名不能为空");
        }
        if (StringUtils.isEmpty(password)) {
            return RestResponse.fail("密码不能空");
        }
        if (StringUtils.isEmpty(appCode)) {
            return RestResponse.fail("系统编码不能为空");
        }
        RestResponse response = null;
        JSONObject json = new JSONObject();
        try {
            SysSubappEntity byCode = sysSubappService.findByCode(appCode);
            String privateKey = byCode.getPrivateKey();
            PwdCheck pwdCheck = appLoginService.doLogin(userName, password, privateKey);
            HttpSession session = request.getSession();
            if (pwdCheck.isSuccess()) {
                session.setAttribute("userId", pwdCheck.getUserId());
                session.setAttribute("platform_cur_user_id_in_session", pwdCheck.getUserId());
                response = RestResponse.succeed(pwdCheck);
            } else {
                response = RestResponse.fail(pwdCheck.getErrorMessage());
            }
        } catch (Exception e) {
            String errormessage = "登录失败";
            log.error(errormessage, e);
            response = RestResponse.fail(errormessage);
        }
        return response;
    }


    /***
     * 修改密码
     * @param updatePwdVO
     * @return
     */
    @PostMapping("/updatePwd")
    public RestResponse updatePwd(HttpServletRequest request, @RequestBody UpdatePwdVO updatePwdVO) {
        String ios = request.getHeader("ios");
        RestResponse restResponse = null;
        SysSubappEntity byCode = sysSubappService.findByCode("android");
        String privateKey = null;
        try {
            if ("1".equals(ios)) {
                privateKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMfWwCmZe2rPLd8q" +
                        "2GT1cGqOkV4LUv+Xzw4peuMENkYSQrmevmPMz7p0RszW90cWZ1WCZVcz6MbZWS/j" +
                        "keILkZNnjRJRncWSZiqWwDs0QAJdWYFYRQ2oqKDazVzlWirEcXbhXmIlrETCYfvA" +
                        "eWkMNMmQgAMTJkuXeH/sg1v6Fe//AgMBAAECgYEAvG22hcMNxzmRFEOPBSsUk7TY" +
                        "RufAm/Ylq0HbeGFJV6ryNZoEBZBiMnpfI9hyExqB1vP74Ey26YCZgvk+XfjwinVm" +
                        "ieaAnGLmyFbOsQxV84Sa5MAtDfoOj1Za9CzXPaEXsK3HxE8zwuDgJ020oNstC87l" +
                        "gWybYaVt7nuX4zRAr/ECQQDi/7e5FMfYyASYKrcKVv+GBGC+sQoAgaQHX+3kUgUp" +
                        "1yRXzc+2VrwxOd0Wqg8XrnM5wtbAtDyYaujpQcaGUZd5AkEA4V66+N44TzcWtrDk" +
                        "W5gN8gwbKhPRHoUyH1me8c45thrmuZobs0MdU181hPPPKX+NMWUkl1xUM44/M4R4" +
                        "ETdNNwJASl5a87ECNFx7XNsJssKD3oVKqM7ZpwbSFXRxPM8+T9HjXzzXYzaRW1NI" +
                        "wqceYLTPnUnfD608+PZ1rg3Vm6XZiQJBAKcwSXBaGlfZvEXnUGEKmj3X8Ubz0Izd" +
                        "ruNG7vzfSjzoFAXYZ3hC77xrwx5QaHyWnT3plI2c9vIQMp6bRR8wcV0CQGUCQz/2" +
                        "nSNMnHcn7Mqf8Cm/68bWFUK3e25frALjH447Uzp5xaJ4bu9kO0vHEpUs59q/5POk" +
                        "xqI6dh1UV2nWoTs=";
            } else {
                privateKey = byCode.getPrivateKey();
            }
            String odPwd = PlatformRSAUtils.decrypt(updatePwdVO.getOldPwd(), privateKey);
            String nwPwd = PlatformRSAUtils.decrypt(updatePwdVO.getNewPwd(), privateKey);
            CertificationEntity certificationEntity = PlatformAPI.getOrgAPI().getUserAPI().updateCertification(updatePwdVO.getUserId(), odPwd, nwPwd);
            restResponse = RestResponse.succeed(certificationEntity);
        } catch (Exception e) {
            String errormessage = "修改密码失败";
            log.error(errormessage, e);
            restResponse = RestResponse.fail(errormessage);
        }
        return restResponse;
    }

    /***
     * 查看个人信息
     * @param userId
     * @return
     */
    @GetMapping("/userInfo")
    public RestResponse getUserInfo(@RequestParam("userId") String userId) {
        RestResponse response = null;
        try {
            UserEntity user = PlatformAPI.getOrgAPI().getUserAPI().getUser(userId);
            RegistUserVo registUserVo=new RegistUserVo();
            registUserVo.setDivision(user.getExtend1());
            registUserVo.setIdNumber(user.getIdCard());
            registUserVo.setMobilePhone(user.getMobilePhone());
            registUserVo.setRelName(user.getUserName());
            registUserVo.setUserName(user.getUserName());
            registUserVo.setUnit(user.getExtend2());
            //FwUserEntity fwUserEntity = fwUserService.findByUserId(userId);
            response = RestResponse.succeed(registUserVo);
        } catch (Exception e) {
            String errorMessage = "查询信息失败";
            log.error(errorMessage, e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }
    /***
     * 注册app
     */
    @PostMapping("/register")
    public RestResponse registerUser(@RequestBody RegistUserVo registUserVo){
        if (registUserVo == null) {
            return RestResponse.fail("保存用户信息不能为空");
        }
        RestResponse restResponse = null;
        try{
            if(!StringUtils.isEmpty(registUserVo.getMobilePhone())){
                UserEntity userByCode = PlatformAPI.getOrgAPI().getUserAPI().getValidUserByUserCode(registUserVo.getMobilePhone());
                if(userByCode!=null){
                    return RestResponse.fail("手机号已存在");
                }
            }
            if(!StringUtils.isEmpty(registUserVo.getIdNumber())){
                List<UserEntity> userEntity = appLoginService.checkIdCard(registUserVo.getIdNumber());
                if(userEntity!=null){
                    return RestResponse.fail("身份号已存在");
                }
            }
            appLoginService.registUser(registUserVo);
            restResponse=RestResponse.succeed("注册成功");

        }catch (Exception e){
            String errorMessage = "注册失败";
            log.error(errorMessage, e);
            restResponse = RestResponse.fail(errorMessage);
        }
        return restResponse;
    }

    /**
     * 行政区划
     *
     * @return
     */
    @GetMapping("divisions/{divisionid}/subdivisions")
    public RestResponse getDisvion(@PathVariable("divisionid") String divisionId) {
        RestResponse restResponse = null;
        try {
            List<DivisionEntity> subDivisions = PlatformAPI.getDivisionAPI().getSubDivisions(divisionId);
            restResponse = RestResponse.succeed(subDivisions);
        } catch (Exception e) {
            String errormessage = "查询失败";
            log.error(errormessage, e);
            restResponse = RestResponse.fail(errormessage);
        }
        return restResponse;
    }
}
